package com.ugold.web.advice;

import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ugold.web.common.Result;
import com.ugold.web.common.exception.ErrorEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * 异常信息统一处理（无法处理404）
 * 
 * @author dingjian
 *
 */
@ControllerAdvice(value = { "com.ugold.web.controller" })
@Slf4j
public class ErrorAdvice {

	@ExceptionHandler
	@ResponseBody
	public Result<?> exceptionHandler(Exception e) {
		log.error(e.getMessage());
		if (e instanceof HttpMessageNotReadableException) {
			return Result.buildFailureResult(80000, "请求体不是合法的JSON");
		} else if (e instanceof MissingServletRequestParameterException) {
			MissingServletRequestParameterException m = (MissingServletRequestParameterException) e;
			return Result.buildFailureResult(80000, m.getParameterName() + "未提供");
		}
		return Result.buildFailureResult(ErrorEnum.ERROR_SERVICE.getErrorCode(),
				ErrorEnum.ERROR_SERVICE.getErrorMessage());
	}
}
